package com.xul.srb.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xul.common.exception.Assert;
import com.xul.common.result.ResponseEnum;
import com.xul.srb.base.uitl.JwtUtils;
import com.xul.srb.core.enums.BorrowInfoStatusEnum;
import com.xul.srb.core.enums.BorrowerStatusEnum;
import com.xul.srb.core.enums.UserBindEnum;
import com.xul.srb.core.mapper.BorrowInfoMapper;
import com.xul.srb.core.mapper.BorrowerMapper;
import com.xul.srb.core.mapper.IntegralGradeMapper;
import com.xul.srb.core.mapper.UserInfoMapper;
import com.xul.srb.core.pojo.entity.BorrowInfo;
import com.xul.srb.core.pojo.entity.Borrower;
import com.xul.srb.core.pojo.entity.IntegralGrade;
import com.xul.srb.core.pojo.entity.UserInfo;
import com.xul.srb.core.pojo.vo.BorrowInfoApprovalVO;
import com.xul.srb.core.pojo.vo.BorrowerDetailVO;
import com.xul.srb.core.service.BorrowInfoService;
import com.xul.srb.core.service.BorrowerService;
import com.xul.srb.core.service.DictService;
import com.xul.srb.core.service.LendService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 借款信息表 服务实现类
 * </p>
 *
 * @author xul
 * @since 2021-11-06
 */
@Service
public class BorrowInfoServiceImpl extends ServiceImpl<BorrowInfoMapper, BorrowInfo> implements BorrowInfoService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private IntegralGradeMapper integralGradeMapper;

    @Resource
    private DictService dictService;

    @Resource
    private BorrowerService borrowerService;

    @Resource
    private BorrowerMapper borrowerMapper;

    @Resource
    private LendService lendService;

    /**
     * 获取借款额度
     *
     * @param request
     * @return
     */
    @Override
    public BigDecimal getBorrowAmount(HttpServletRequest request) {

        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);
        UserInfo userInfo = userInfoMapper.selectById(userId);
        Assert.notNull(userInfo, ResponseEnum.LOGIN_MOBILE_ERROR);
        Integer integral = userInfo.getIntegral();

        QueryWrapper<IntegralGrade> wrapper = new QueryWrapper<>();
        wrapper.le("integral_start", integral).ge("integral_end", integral);
        IntegralGrade integralGrade = integralGradeMapper.selectOne(wrapper);
        if (integralGrade == null) {
            return new BigDecimal(0);
        }

        return integralGrade.getBorrowAmount();

    }

    /**
     * 提交借款申请
     *
     * @param borrowInfo
     * @param request
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveBorrowInfo(BorrowInfo borrowInfo, HttpServletRequest request) {
        Long userId = JwtUtils.getUserId(request.getHeader("token"));
        UserInfo userInfo = userInfoMapper.selectById(userId);

        // 用户的状态判断
        Assert.isTrue(userInfo.getStatus() == 1, ResponseEnum.LOGIN_LOKED_ERROR);

        // 用户是否绑定
        Assert.isTrue(userInfo.getBindStatus().intValue() == UserBindEnum.BIND_OK.getStatus().intValue(), ResponseEnum.USER_NO_BIND_ERROR);

        // 用户信息是否审批通过
        Assert.isTrue(userInfo.getBorrowAuthStatus().intValue() == BorrowerStatusEnum.AUTH_OK.getStatus().intValue(), ResponseEnum.USER_NO_AMOUNT_ERROR);

        // 判断借款人的金额是否足够
        BigDecimal borrowAmount = this.getBorrowAmount(request);
        Assert.isTrue(borrowAmount.doubleValue() >= borrowInfo.getAmount().doubleValue(), ResponseEnum.USER_AMOUNT_LESS_ERROR);

        // 封装用户信息
        borrowInfo.setUserId(userId);
        borrowInfo.setBorrowYearRate(borrowInfo.getBorrowYearRate().divide(new BigDecimal(100)));
        borrowInfo.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getStatus());
        baseMapper.insert(borrowInfo);
    }

    /**
     * 获取借款申请审批状态
     *
     * @param request
     * @return
     */
    @Override
    public Integer getBorrowerStatus(HttpServletRequest request) {
        Long userId = JwtUtils.getUserId(request.getHeader("token"));
        QueryWrapper<BorrowInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        BorrowInfo borrowInfo = baseMapper.selectOne(wrapper);
        if (borrowInfo == null) {
            // 借款人没有提交信息
            return BorrowInfoStatusEnum.NO_AUTH.getStatus();
        }
        return borrowInfo.getStatus();
    }

    /**
     * 借款信息列表
     *
     * @return
     */
    @Override
    public List<BorrowInfo> getList() {

        List<BorrowInfo> borrowInfoList = baseMapper.getList();
        borrowInfoList.forEach(this::BorrowInfo);
        return borrowInfoList;
    }

    /**
     * 获取借款信息
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> getBorrowDetail(Long id) {
        // 组装借款信息详情
        Map<String, Object> result = new HashMap<>();
        // 获取借款信息表的数据 borrowInfo
        BorrowInfo borrowInfo = baseMapper.selectById(id);
        Assert.notNull(borrowInfo, ResponseEnum.ZWHQJKRXI);
        // 封装特殊字段处理
        this.BorrowInfo(borrowInfo);
        // 获取借款人的信息
        Long userId = borrowInfo.getUserId();
        QueryWrapper<Borrower> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        Borrower borrower = borrowerMapper.selectOne(wrapper);
        BorrowerDetailVO borrowerDetailVOById = borrowerService.getBorrowerDetailVOById(borrower.getId());

        result.put("borrowInfo", borrowInfo);
        result.put("borrower", borrowerDetailVOById);

        return result;
    }

    /**
     * 审批借款信息
     *
     * @param borrowInfoApprovalVO
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void approval(BorrowInfoApprovalVO borrowInfoApprovalVO) {
        // 修改借款人的状态
        Long id = borrowInfoApprovalVO.getId();
        BorrowInfo borrowInfo = baseMapper.selectById(id);
        borrowInfo.setStatus(borrowInfoApprovalVO.getStatus());
        baseMapper.updateById(borrowInfo);

        // 审核通过会产生新的标的 存入相关信息到标的表
        if(borrowInfo.getStatus().intValue() == BorrowInfoStatusEnum.CHECK_OK.getStatus().intValue()){
            // 创建标的
            lendService.createLend(borrowInfo,borrowInfoApprovalVO);
        }
    }

    /**
     * 用于封装借款详情字段的信息
     *
     * @param borrowInfo
     */
    public void BorrowInfo(BorrowInfo borrowInfo) {
        // 还款方式 1-等额本息 2-等额本金 3-每月还息一次还本 4-一次还本
        String returnMethod = dictService.getNameByDictCodeAndValue(borrowInfo.getReturnMethod(), "returnMethod");
        // 资金用途
        String moneyUse = dictService.getNameByDictCodeAndValue(borrowInfo.getMoneyUse(), "moneyUse");
        String status = BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus());
        borrowInfo.getParam().put("returnMethod", returnMethod);
        borrowInfo.getParam().put("moneyUse", moneyUse);
        borrowInfo.getParam().put("status", status);
    }
}
